package com.xunqi.ware.service.impl;

import com.xunqi.common.constant.WareConstant;
import com.xunqi.ware.entity.PurchaseDetailEntity;
import com.xunqi.ware.service.PurchaseDetailService;
import com.xunqi.ware.service.WareSkuService;
import com.xunqi.ware.vo.MergeVo;
import com.xunqi.ware.vo.PurchaseDoneVo;
import com.xunqi.ware.vo.PurchaseItemDoneVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.common.utils.PageUtils;
import com.xunqi.common.utils.Query;

import com.xunqi.ware.dao.PurchaseDao;
import com.xunqi.ware.entity.PurchaseEntity;
import com.xunqi.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        String key = params.get("key")==null?"":params.get("key").toString();
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("id",key).or().like("assignee_id",key)
                    .or().like("assignee_name",key).or().like("phone",key)
                    .or().like("priority",key).or().like("amount",key);
        }
        String status = params.get("status").toString();
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
             purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();

        }
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).filter(i->
                i.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
        ).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建或者已分配
        List<PurchaseEntity> collect = ids.stream().map(i -> {
            PurchaseEntity byId = this.getById(i);
            byId.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            return byId;
        }).filter(i->
                i.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                || i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
        ).map(i->{
            i.setStatus(WareConstant.PurchaseStatusEnum.BUYING.getCode());
            return i;
        }).collect(Collectors.toList());

        //2.改变采购单状态
        this.updateBatchById(collect);

        //3.改变采购项的状态
        collect.forEach(item->{
           List<PurchaseDetailEntity> entities =  purchaseDetailService.listDetailBy(item);
            List<PurchaseDetailEntity> collect1 = entities.stream().map(i -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(i.getId());
                detailEntity.setStatus(i.getStatus());
                return detailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();
        //1.改变采购项的状态
        Boolean flag =true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        ArrayList<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag= false;
                detailEntity.setStatus(item.getStatus());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            detailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);

        //2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseDetailStatusEnum.FINISH.getCode():WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);



        //3.将成功采购的进行入库
    }

}